package com.example.yian.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.yian.entity.SecurityRisk;
import com.example.yian.mapper.SecurityRiskMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;

@Service
public class SecurityRiskService {

    @Autowired
    private SecurityRiskMapper securityRiskMapper;

    private static final Logger log = LoggerFactory.getLogger(SecurityRiskReportService.class);

    public SecurityRisk addSecurityRisk(String image, String chatId, String textId, String supplementContents, Long userId) {
        SecurityRisk securityRisk = new SecurityRisk();
        securityRisk.setUserId(userId);
        securityRisk.setImage(image);
        securityRisk.setChatId(chatId);
        securityRisk.setTextId(textId);
        securityRisk.setSupplementContents(supplementContents);
        securityRiskMapper.insert(securityRisk);
        return securityRisk;
    }

    public Optional<SecurityRisk> getSecurityRiskWithDetails(Long risksId) {
        return Optional.ofNullable(securityRiskMapper.selectById(risksId));
    }

    /**
     * 根据user_id分页获取隐患列表
     * @param userId 用户ID
     * @param page 当前页码
     * @param size 每页数量
     * @return 分页后的隐患列表数据
     */
    public IPage<SecurityRisk> getRiskListsByUserId(Long userId, int page, int size, String startTime, String endTime,int selectFlag) {
        int offset = (page - 1) * size;
        Page<SecurityRisk> pageInfo = new Page<>(page, size);
        startTime = startTime + " 00:00:00";
        endTime = endTime + " 23:59:59";

        log.info("startTime:{}, endTime:{}", startTime, endTime);
        List<SecurityRisk> risks = securityRiskMapper.getRiskListByUserIdWithPagination(pageInfo, userId, startTime, endTime, size, offset, selectFlag);
        pageInfo.setRecords(risks);


        return pageInfo;
    }

    /**
     * 根据用户ID统计自然周内每天的隐患数量
     * @param userId 用户ID
     * @return 每天的隐患数量映射
     */
    public Map<LocalDate, Long> countRisksByDayOfWeekForUser(Long userId) {
        LocalDate now = LocalDate.now();
        LocalDate startOfWeek = now.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        LocalDate endOfWeek = now.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));

        // 转换日期为Timestamp (这部分逻辑可能需要根据实际情况调整，确保与数据库查询兼容)
        Date startDate = Date.from(startOfWeek.atStartOfDay(ZoneId.systemDefault()).toInstant());
        Date endDate = Date.from(endOfWeek.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant());

        // 调用Mapper层方法获取数据
        List<Map<String, Object>> riskCounts = securityRiskMapper.countRisksByUserIdAndDateRange(userId, new Timestamp(startDate.getTime()), new Timestamp(endDate.getTime()));

        // 处理结果
        Map<LocalDate, Long> dailyCounts = new LinkedHashMap<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); // 请根据实际数据库中日期字段的格式进行调整
        dateFormat.setTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault().getId())); // 设置时区以匹配系统默认时区

        for (Map<String, Object> riskCount : riskCounts) {
            String dateString = (String) riskCount.get("date"); // 假设从数据库获取的是字符串形式的日期
            LocalDate date;
            try {
                Date tempDate = dateFormat.parse(dateString);
                date = tempDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            } catch (Exception e) {
                // 异常处理，例如打印错误信息或跳过该条记录
                System.err.println("Error parsing date: " + dateString);
                continue;
            }
            Long count = (Long) riskCount.get("count");
            dailyCounts.put(date, count);
        }
        return dailyCounts;
    }

    public Map<String, Object> addSearchTextToRisk(SecurityRisk risk, String searchText) {
        Map<String, Object> data = new HashMap<>();
        data.put("id", risk.getId());
        data.put("userId", risk.getUserId());
        data.put("image", risk.getImage());
        data.put("chatId", risk.getChatId());
        data.put("textId", risk.getTextId());
        data.put("supplementContents", risk.getSupplementContents());
        data.put("deadline", "");
        data.put("createdAt", risk.GetCreatedAt());
        data.put("updatedAt", risk.GetUpdatedAt());
        data.put("searchText", searchText);

        return data;
    }
}

